<script lang="ts" setup>
import { ref, Ref, reactive } from 'vue';
import detailedCase from '@/compontent/detailedCase.vue'; // 导入 detailedCase 组件
import { getAllMediators } from '@/axios/mediator/mediatorReq';
import  Mediator  from '@/types/response/mediator';
import { ElMessage } from 'element-plus'
import {getCaseByCaseStatus, adminExamine} from '@/axios/case/caseReq'
import { Case, CaseStatus } from '@/types/response/case';
import Notice from '@/utils/notice';

const mediators: Ref<Mediator[]> = ref([]);

const cases:Ref<Case[]> = ref([]);
let solveDialog:{
  visible:boolean,
  mediatorId:number,
  case:Case,
  assignMediator:Function,
  look:(c:Case)=>void,
  close:Function,
}=reactive({
    visible: false,
    case:null,
    mediatorId:null,
    mediator:new Mediator(),
    async assignMediator(){
      let c=solveDialog.case;
      if(solveDialog.case==null||solveDialog.mediatorId==null){
        Notice.error("请选择案件和调解员");
        return;
      }
      const success = await adminExamine(1,solveDialog.case.caseId, solveDialog.mediatorId); // 假设 agree 为 1 表示分配调解员
      if(success){
        Notice.success("分配成功");
        cases.value.splice(cases.value.indexOf(c),1);
      }
      solveDialog.close();
    },
    look(c:Case){
      solveDialog.visible = true;
      solveDialog.case = c;
    },
    close(){
      solveDialog.visible = false;
      solveDialog.mediatorId=null;
      solveDialog.case = null;
    }
})

const formLabelWidth = '140px'
const fetchMediators = async () => {
  mediators.value = await getAllMediators();//获得所有的调解人
}

fetchMediators();

const getCases = async () => {
  try {
    let result = await getCaseByCaseStatus(CaseStatus.applied);
    result.sort((a, b) => new Date(a.createdTime).getTime() - new Date(b.createdTime).getTime());
    cases.value = result;
    console.log('Cases loaded:', cases.value);
  } catch (error) {
    console.error("Error fetching cases:", error);
  }
};
getCases();

// 控制详细案件弹窗
let detailedDialog=reactive({
  visible:false,
  case:new Case(),
  look(c:Case){
    detailedDialog.case=c;
    detailedDialog.visible = true;
  },
  close(){
    detailedDialog.visible =false;
  }
})
const handleRejectCase = async (caseId: number) => {
  try {
    const success = await adminExamine(0, caseId, null); // 假设 agree 为 0 表示驳回，mediatorId 为 null
    if (success) {
      ElMessage.success('案件已驳回');
      cases.value.splice(cases.value.findIndex(item=>item.caseId==caseId), 1);
    } else {
      // 处理失败的情况
      ElMessage.error('驳回案件失败');
    }
  } catch (error) {
    console.error("Error rejecting case:", error);
    ElMessage.error('系统错误，请稍后再试');
  }
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>待办事项</span>
      </div>
    </template>

    <el-scrollbar max-height="400px">
      <el-table :data="cases" style="width: 100%">
        <el-table-column label="申请人" prop="applicant.name"></el-table-column>
        <el-table-column label="所属事务所" prop="applicant.lawnSite"></el-table-column>
        <el-table-column label="被申请人" prop="respondent.name"></el-table-column>
        <el-table-column label="欠款总金额" prop="debt.amount"></el-table-column>
        <el-table-column label="案件创建时间" prop="createdTime"></el-table-column>
        <el-table-column label="案由" prop="cause"></el-table-column>
        <el-table-column label="操作" width="350">
          <template #default="scope">
            <el-button type="primary" @click="detailedDialog.look(scope.row)">详情</el-button>
            <el-button type="primary" @click="solveDialog.look(scope.row)">处理</el-button>
            <el-button type="primary" @click="handleRejectCase(scope.row.caseId)">驳回</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="没有数据" />
        </template>
      </el-table>
    </el-scrollbar>

       <!-- 详细案件弹窗 -->
    <detailed-case
      :caseId="detailedDialog.case.caseId"
      :case="detailedDialog.case"
      v-model="detailedDialog.visible"
    />
  </el-card>
  <el-dialog v-model="solveDialog.visible" title="分配调解员" width="500">
    <el-form>
      <el-form-item label="分配给：" :label-width="formLabelWidth">
        <el-select v-model="solveDialog.mediatorId" placeholder="请选择一个调解员">
          <el-option v-for="mediator in mediators" :key="mediator.mId" :label="mediator.name" :value="mediator.mId" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="solveDialog.close()">取消</el-button>
        <el-button type="primary" @click="solveDialog.assignMediator()">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>